/******************************************************************************
 *
 * ngcap - network sniffer using raw sockets
 *
 * Author:        cr
 * E-mail:        cr.at.netgarage.org
 * WWW:           http://www.netgarage.org
 * Copyright (C): 2009 by cr
 *
 * This file is part of ngcap.
 *
 * ngcap is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ngcap is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ngcap.  If not, see <http://www.gnu.org/licenses/>.
 *
 *****************************************************************************/

#ifndef _PACKETHANDLER_HPP_
#define _PACKETHANDLER_HPP_
#include "packet.hpp"
#include <queue>
//#include <sys/socket.h>
//#include <netinet/in.h>
//#include <netpacket/packet.h>
//#include <net/ethernet.h>
#include "rawsocket.hpp"
//#include "filter.hpp"
//#include "trace.hpp"


class PacketHandler
{
public:
    PacketHandler(PacketFilter* f) : receiving(false), filtered(false), filter(f)
    {
        Trace t("Packethandler");
        try{
            sock=new RawSocket;
        } catch (SocketError& ex)
        {
            t.log(ex.what());
            throw;
        }
    }
    ~PacketHandler()
    {
        delete sock;
    }
    void startThreads(PacketHandler* p)
    {
        Trace t("Packethandler::startThreads");
        receiving=true;
        pthread_mutex_init(&qmutex, NULL);
        pthread_mutex_init(&cmutex, NULL);
        pthread_cond_init(&notempty, NULL);
        pthread_create(&receivethread, NULL, receivePacketThread, p);
        pthread_create(&handlethread, NULL, handlePacketThread, p);
        pthread_join(receivethread, NULL);
        pthread_join(handlethread, NULL);
    }
    bool newPackets() { return packets.size()>0; }
    void receivePackets();
    static void* receivePacketThread(void* p)
    {
        static_cast<PacketHandler*>(p)->receivePackets();
        return 0;
    }
    void handlePackets();
    static void* handlePacketThread(void* p)
    {
        static_cast<PacketHandler*>(p)->handlePackets();
        return 0;
    }
    capturedPacket analyzePacket(Packet* p);

private:
    bool receiving;
    bool filtered;
    PacketFilter* filter;
    std::queue<Packet*> packets;
    pthread_t receivethread;
    pthread_t handlethread;
    pthread_mutex_t qmutex;
    pthread_mutex_t cmutex;
    pthread_cond_t notempty;
    RawSocket* sock;
    RawSocket rawsock;
};

#endif
